<template>
  <div style="overflow-x: hidden; overflow-y: auto; height: 95%">
    <!-- 已排区 -->
    <div id="alreadyOrdered">
      <a-form size="small" :model="pageData" layout="inline" style="margin-left: 24px">
        <a-form-item label="车间">
          <a-select v-model="pageData.workshopId2" style="width: 120px" class="bacClass" allow-clear>
            <a-option :value="1">染部A</a-option>
            <a-option :value="2">染部B</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="流转卡号">
          <a-input allow-clear style="width: 120px" class="bacClass" v-model="pageData.flowCardCode2" />
        </a-form-item>
        <div style="display: flex">
          <a-button type="primary" style="margin-right: 28px" @click="doRefresh2()">查询</a-button>
          <a-button type="outline" style="margin-right: 28px" @click="editOrder()">修改</a-button>
        </div>
      </a-form>
      <div class="divInterval"></div>
      <div class="divCenter">
        <a-button class="buttonLeft" type="primary">已<br />排<br />区</a-button>
        <a-spin :loading="pageData.pageLoading2" tip="加载中" dot style="width: 95%; z-index: 999">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
            style="height: 400px; width: 100%" :suppressDragLeaveHidesColumns="true" rowSelection="multiple"
            @grid-ready="gridReady2" :defaultColDef="defaultColDef" class="ag-theme-alpine"
            :rowData="pageData.arrangedList" :columnDefs="tableColumns2" :localeText="localeText1"
            :rowDragManaged="true" :animateRows="true" @rowDragEnd="onRowDragEnd">
          </AgGridVuesCopys>
        </a-spin>
      </div>
    </div>
    <!-- 调转位置图标按钮 -->
    <div id="gang">
      <icon-double-down @click="transferDown()" style="margin-left: 50%" :strokeWidth="3" :size="22" />
    </div>
    <!-- 未排区 -->
    <div id="notOrdered">
      <a-form size="small" :model="pageData" layout="inline" style="margin-left: 24px">
        <a-form-item label="车间">
          <a-select v-model="pageData.workshopId" style="width: 120px" class="bacClass" allow-clear>
            <a-option :value="1">染部A</a-option>
            <a-option :value="2">染部B</a-option>
          </a-select>
        </a-form-item>
        <!-- <a-form-item label="缸型">
          <a-select v-model="pageData.cylinderTypes" style="width: 100px" class="bacClass" allow-clear>
            <a-option value="E缸">E缸</a-option>
            <a-option value="S缸">S缸</a-option>
          </a-select>
        </a-form-item> -->
        <a-form-item label="流转卡号">
          <a-input allow-clear style="width: 120px" class="bacClass" v-model="pageData.flowCardCode" />
        </a-form-item>
        <a-button type="primary" style="margin-right: 28px" @click="doRefresh()">查询</a-button>
        <a-form-item label="已排">
          <a-input style="width: 70px" class="bacClass" v-model="pageData.arrangedSum" disabled />
        </a-form-item>
        <a-form-item label="第1位">
          <a-input style="width: 70px" class="bacClass" v-model="pageData.onePlace" disabled />
        </a-form-item>
        <a-form-item label="第2位">
          <a-input style="width: 70px" class="bacClass" v-model="pageData.twoPlace" disabled />
        </a-form-item>
        <a-form-item label="未排">
          <a-input style="width: 70px" class="bacClass" v-model="pageData.unscheduledSum" disabled />
        </a-form-item>
        <a-form-item label="设备">
          <a-input style="width: 70px" class="bacClass" v-model="pageData.equipment" disabled />
        </a-form-item>
        <a-form-item label="运行">
          <a-input style="width: 70px" class="bacClass" v-model="pageData.working" disabled />
        </a-form-item>
        <a-form-item label="空闲">
          <a-input style="width: 70px" class="bacClass" v-model="pageData.free" disabled />
        </a-form-item>
        <a-button type="primary" @click="equipmentStart()">设备开机</a-button>
      </a-form>
      <div class="divInterval"></div>
      <div class="divCenter">
        <a-button class="buttonLeft" type="primary" style="margin-top: -10px">未<br />排<br />区</a-button>
        <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="width: 95%; z-index: 999; margin-bottom: 10px">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
            style="height: 400px; width: 100%" :suppressDragLeaveHidesColumns="true" rowSelection="multiple"
            @grid-ready="gridReady" :defaultColDef="defaultColDef" class="ag-theme-alpine"
            :rowData="pageData.unscheduledList" :columnDefs="tableColumns" :localeText="localeText1">
          </AgGridVuesCopys>
        </a-spin>
      </div>
    </div>
  </div>
  <!-- 排产弹窗 -->
  <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false"
    :visible="pageData.apsShow" :ok-loading="pageData.pageLoading" unmountOnClose placement="bottom" height="100%"
    @ok="apsOk" @cancel="pageData.apsShow = false">
    <template #title>
      {{ pageData.sideTitle }}
    </template>
    <div>
      <table class="table" v-if="pageData.sideTitle != '已排产顺序调整'">
        <thead>
          <tr>
            <th>排产卡号</th>
            <th>{{ dataForm.flowCardCode.split('_')[0] }}</th>
            <th>缸型</th>
            <th>{{ dataForm.cylinderType }}</th>
            <th>管型</th>
            <th>{{ dataForm.castNum }}</th>
            <th>匹数</th>
            <th>{{ dataForm.houseNum }}</th>
            <th>重量</th>
            <th>{{ dataForm.flowCardWeight }}</th>
          </tr>
        </thead>
      </table>
      <!-- 机台排产 -->
      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
        style="width: 100%; margin-top: 5px" :style="{ height: pageData.sideTitle == '车间任务发布' ? '510px' : '720px' }"
        :suppressDragLeaveHidesColumns="true" rowSelection="multiple" @grid-ready="apsGridReady"
        :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="pageData.apsList" :columnDefs="aspTableColumns"
        :localeText="localeText1" :suppressMovableColumns="true">
      </AgGridVuesCopys>
      <!-- 流转卡工序时间计算 -->
      <AgGridVuesCopys v-if="pageData.sideTitle == '车间任务发布'" :rowHeight="33" :headerHeight="33"
        :suppressCopyRowsToClipboard="true" style="height: 150px; width: 100%; margin-top: 30px"
        :suppressDragLeaveHidesColumns="true" rowSelection="multiple" @grid-ready="timeGridReady"
        :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="pageData.timeList"
        :columnDefs="timeTableColumns" :localeText="localeText1">
      </AgGridVuesCopys>
      <table v-if="pageData.sideTitle == '车间任务发布'" style="border: 1px solid #babfc7; text-align: left; border-top: 0px">
        <thead>
          <tr>
            <th style="padding: 5px">订单状态：CF超反</th>
            <th style="padding: 5px">生产周期：4天</th>
            <th style="padding: 5px">此单计划：<span style="color: #64dd3f">8天</span></th>
            <th style="padding: 5px">接单结果：<span style="color: red">-1</span></th>
          </tr>
        </thead>
      </table>
    </div>
  </a-drawer>

  <!-- 设备开机 -->
  <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false"
    :visible="pageData.equipmentShow" :ok-loading="pageData.pageLoading" unmountOnClose placement="bottom" height="100%"
    @ok="apsOk" @cancel="pageData.equipmentShow = false">
    <template #title> 设备开停 </template>
    <template #footer><a-button @click="pageData.equipmentShow = false">关闭</a-button></template>
    <div>
      <div style="display: flex; justify-content: space-between">
        <a-form size="small" :model="dataForm" layout="inline">
          <a-form-item label="车间">
            <a-select v-model="dataForm.workshopId" style="width: 200px" class="bacClass" allow-clear>
              <a-option :value="1">染部A</a-option>
              <a-option :value="2">染部B</a-option>
            </a-select>
          </a-form-item>
        </a-form>
        <Toolbar style="float: right" :items="['查询']" @select="equipmentQuery()"></Toolbar>
      </div>
      <!-- 机台开停 -->
      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" style="height: 650px; width: 100%; margin-top: 5px"
        :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="equipmentGridReady"
        :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="pageData.equipmentList"
        :columnDefs="equipmentTableColumns" :localeText="localeText1" :suppressMovableColumns="true">
      </AgGridVuesCopys>
      <table class="table" style="border-top: 0px">
        <thead>
          <tr>
            <th :colspan="10" style="background-color: #dde2eb; border-top: 0px">机台汇总</th>
          </tr>
          <tr>
            <th>机台总数</th>
            <th>{{ pageData.equipmentList.length }}</th>
            <th>开机台数</th>
            <th>{{
        pageData.equipmentList.length > 0
          ? pageData.equipmentList.filter((o: any) => o.status == 1).length
          : 0
      }}</th>
            <th>开机日产能</th>
            <th style="color: #64dd3f">{{
          pageData.equipmentList.length > 0
            ? pageData.equipmentList
              .filter((o:any) => o.status == 1)
              .reduce((total: any, equipment: any) => total + equipment.machineNum, 0) + 'KG'
            : '0KG'
        }}</th>
            <th>未开台数</th>
            <th>{{
          pageData.equipmentList.length > 0
            ? pageData.equipmentList.filter((o: any) => o.status == 0).length
            : 0
        }}</th>
            <th>损失产能</th>
            <th style="color: red">{{
          pageData.equipmentList.length > 0
            ? pageData.equipmentList
              .filter((o: any) => o.status == 0)
              .reduce((total: any, equipment: any) => total + equipment.machineNum, 0) + 'KG'
              : '0KG'
              }}</th>
          </tr>
        </thead>
      </table>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, onMounted } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { color } from 'echarts'
import ReturnGoodsOutVue from '@/views/wh/ReturnGoodsOut.vue'
import { CellRangeType } from 'ag-grid-community'
import { invalid } from 'moment'
import { Post } from '@/api/basedata'
import { log } from 'echarts/types/src/util/log'

const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const pageData: any = reactive({
  apsShow: false,
  equipmentShow: false,
  sideTitle: '',
  rHeight: 0,
  arrangedList: [],
  unscheduledList: [],
  flowList: [],
  apsList: [],
  timeList: [],
  equipmentList: [],
  pageLoading: false,
  pageLoading2: false,
  arrangedSum: '',
  onePlace: '',
  twoPlace: '',
  unscheduledSum: '',
  equipment: '',
  working: '',
  free: '',
  workshopId: null,
  workshopId2: null,
  flowCardCode: '',
  flowCardCode2: '',
})

const dataForm: any = reactive({
  flowCardCode: '',
  castNum: '',
  houseNum: '',
  flowCardWeight: '',
  cylinderType: '',
  machineCodes: [],
  workshopId: null,
})

const defaultColDef: any = {
  sortable: true,
  resizable: true,
  filter: true,
}

// 未排产表格
const gridOption = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
}
let tableColumns: any = [
  { headerName: '管型', field: 'castNum', width: 100 },
  {
    headerName: '色样',
    field: 'colorSample',
    width: 100,
    cellRenderer: {
      template: ` <a-image v-if="val.colorSample" :src="val.colorSample" /> 
                  <span v-if="!val.colorSample"></span>`,
      setup(props: any) {
        const val = ref(props.params.data)
        return {
          val,
        }
      },
    },
  },
  { headerName: '色称', field: 'colorName', width: 100 },
  { headerName: '流转卡号', field: 'flowCardCode', width: 100 },
  { headerName: '匹数', field: 'houseNum', width: 100 },
  { headerName: '重量(KG)', field: 'flowCardWeight', width: 100 },
  { headerName: '色号', field: 'colorCode', width: 100 },
  { headerName: '已用天数', field: 'dd', width: 100 },
  { headerName: '预计出缸', field: 'dd', width: 100 },
  {
    headerName: 'HOLD单状态',
    field: 'holdState',
    width: 100,
    cellRenderer: {
      template: `<div>{{ val.holdState == 0 ? '否' : '是' }}</div>`,
      setup(props: any) {
        let val = ref(props.params.data)
        return {
          val,
        }
      },
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == 0 ? '否' : params.value == 1 ? '是' : ''
      },
    },
  },
  { headerName: '配方状态', field: 'dyingFormulaStatus', width: 100 },
  { headerName: '复办状态', field: 'bathRatioStatus', width: 100 },
  { headerName: '当前工段', field: 'dd', width: 100 },
  { headerName: '当前工序', field: 'dd', width: 100 },
  { headerName: '当前进度', field: 'dd', width: 100 },
  {
    headerName: '工艺流程',
    //工序动态表头
    children: [],
  },
  {
    headerName: '操作',
    field: 'action',
    width: 100,
    pinned: 'right',
    cellRenderer: {
      template: `<a-button type="primary" size="mini" @click="c">排产</a-button>`,
      setup(props: any) {
        const c = () => {
          apsMethod(props.params.data)
        }
        return {
          c,
        }
      },
    },
  },
]

// 已排产表格
const gridOption2 = ref()
const gridReady2 = (params: any) => {
  gridOption2.value = params.api
}
let tableColumns2: any = [
  {
    field: '',
    pinned: 'left',
    rowDrag: (params: any) => {
      return !(params.data.machineOrder == null)
    },
    width: 50,
  },
  { headerName: '管型', field: 'castNum', width: 100 },
  { headerName: '染缸号', field: 'machineCode', width: 100 },
  { headerName: '排位', field: 'machineOrder', width: 100 },
  {
    headerName: '色样',
    field: 'colorSample',
    width: 100,
    cellRenderer: {
      template: ` <a-image v-if="val.colorSample" :src="val.colorSample" /> 
                  <span v-if="!val.colorSample"></span>`,
      setup(props: any) {
        const val = ref(props.params.data)
        return {
          val,
        }
      },
    },
  },
  { headerName: '色称', field: 'colorName', width: 100 },
  { headerName: '流转卡号', field: 'flowCardCode', width: 100 },
  { headerName: '匹数', field: 'houseNum', width: 100 },
  { headerName: '重量(KG)', field: 'flowCardWeight', width: 100 },
  { headerName: '色号', field: 'colorCode', width: 100 },
  { headerName: '已用天数', field: 'dd', width: 100 },
  { headerName: '预计出缸', field: 'dd', width: 100 },
  {
    headerName: 'HOLD单状态',
    field: 'holdState',
    width: 100,
    cellRenderer: {
      template: `<div>{{ val.holdState == 0 ? '否' : '是' }}</div>`,
      setup(props: any) {
        let val = ref(props.params.data)
        return {
          val,
        }
      },
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == 0 ? '否' : params.value == 1 ? '是' : ''
      },
    },
  },
  { headerName: '配方状态', field: 'dyingFormulaStatus', width: 100 },
  { headerName: '复办状态', field: 'bathRatioStatus', width: 100 },
  { headerName: '当前工段', field: 'dd', width: 100 },
  { headerName: '当前工序', field: 'dd', width: 100 },
  { headerName: '当前进度', field: 'dd', width: 100 },
  { headerName: '工艺流程', children: [] },
  {
    headerName: '操作',
    field: 'action',
    width: 100,
    pinned: 'right',
    cellRenderer: {
      template: `<a-button type="primary" size="mini" @click="c">转机台</a-button>`,
      setup(props: any) {
        const c = () => {
          editTurntable(props.params.data)
        }
        return {
          c,
        }
      },
    },
  },
]

//机台排产表格
const apsGridOption = ref()
const apsGridReady = (params: any) => {
  apsGridOption.value = params.api
}
const aspTableColumns: any = ref([])

//工序时间表格
const timeGridOption = ref()
const timeGridReady = (params: any) => {
  timeGridOption.value = params.api
}
let timeTableColumns: any = [
  {
    headerName: '流转卡工序时间计算',
    headerClass: 'custom-header-class',
    //动态表头
    children: [],
  },
]

//设备开停 表格
const equipmentGridOption = ref()
const equipmentGridReady = (params: any) => {
  equipmentGridOption.value = params.api
}
let equipmentTableColumns: any = [
  { headerName: '机台号', field: 'machineCode', width: 300 },
  { headerName: '机台名称', field: 'machineName', width: 300 },
  { headerName: '产能', field: 'machineNum', width: 300 },
  {
    headerName: '状态',
    field: 'status',
    width: 300,
    cellRenderer: {
      template: `<a-switch checked-color="#64dd3f" unchecked-color="#b7b3b3" v-model="val.status"
                      :checked-value="1" :unchecked-value="0" style="width:60px;" @click="c">
                    <template #checked><span style="font-size:15px;color:black;margin-left:15px;">Y</span></template>
                    <template #unchecked><span style="font-size:15px;color:black;">N</span></template>
                 </a-switch>`,
      setup(props: any) {
        let val = ref(props.params.data)
        const c = () => {
          equipmentCheck(props.params.data)
        }
        return {
          c,
          val,
        }
      },
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == 0 ? 'N' : params.value == 1 ? 'Y' : ''
      },
    },
  },
]

const Query = () => {
  doRefresh()
  doRefresh2()
}

//未排区 查询
function doRefresh() {
  pageData.pageLoading = true
  get({
    url: 'aps/workSequenceTask/findTaskByMachinTypeAndStatus',
    data: {
      status: 0,
      machineTypeId: 1,
      workshopId: pageData.workshopId ? pageData.workshopId : 0,
      flowCardCode: pageData.flowCardCode,
    },
  })
    .then(({ data, code }: any) => {
      if (code === 200) {
        columnsName(tableColumns, data)
        tableColumns = [...tableColumns]
        pageData.unscheduledList = data
        pageData.unscheduledSum = pageData.unscheduledList.length
        pageData.equipment = '染色机'
        gridOption.value.setRowData(data)
      }
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading = false
    })
}

//已排区 查询
function doRefresh2() {
  pageData.pageLoading2 = true
  get({
    url: 'aps/workSequenceTask/findTaskByMachinTypeAndStatus',
    data: {
      status: 1,
      machineTypeId: 1,
      workshopId: pageData.workshopId2 ? pageData.workshopId2 : 0,
      flowCardCode: pageData.flowCardCode2,
    },
  })
    .then(({ data, code }: any) => {
      if (code === 200) {
        columnsName(tableColumns2, data)
        tableColumns2 = [...tableColumns2]
        pageData.arrangedList = data
        pageData.arrangedSum = pageData.arrangedList.length
        pageData.onePlace = pageData.arrangedList.filter((o: any) => o.machineOrder == 1).length
        pageData.twoPlace = pageData.arrangedList.filter((o: any) => o.machineOrder == 2).length
        gridOption2.value.setRowData(data)
      }
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading2 = false
    })
}

// 自定义的单元格渲染器
const customCellRenderer = (params: any) => {
  const flowList = params.data.flowList
  const isExists = flowList && flowList.includes(params.colDef.headerName)
  return isExists ? 'Y' : 'N'
}

// 定义样式函数
const customCellStyle = (params: any) => {
  const flowList = params.data.flowList
  const isExists = flowList && flowList.includes(params.colDef.headerName)
  return isExists ? { backgroundColor: '#64dd3f' } : { backgroundColor: '#b7b3b3' }
}

//工艺流程动态获取子表头数据
const columnsName = (columns: any, data: any) => {
  const childColumns = columns.find((col: any) => col.headerName === '工艺流程')
  if (data.length > 0) {
    childColumns.children = data[0].processNames.map((name: any) => ({
      headerName: name,
      field: '',
      width: 100,
      cellRenderer: customCellRenderer,
      cellStyle: customCellStyle,
    }))
  } else {
    delete childColumns.children
  }
}

//排产 弹窗
const apsMethod = (val: any) => {
  dataForm.flowCardCode = val.flowCardCode + '_' + val.taskId
  dataForm.castNum = val.castNum
  dataForm.houseNum = val.houseNum
  dataForm.flowCardWeight = val.flowCardWeight
  dataForm.cylinderType = val.cylinderType
  pageData.sideTitle = '车间任务发布'
  if (!pageData.workshopId) {
    Message.warning('请先选择车间')
    return
  }
  workshopTask(pageData.workshopId)
  processData(val)
}

// 转机台 弹窗
const editTurntable = (val: any) => {
  dataForm.flowCardCode = val.flowCardCode + '_' + val.taskId
  dataForm.castNum = val.castNum
  dataForm.houseNum = val.houseNum
  dataForm.flowCardWeight = val.flowCardWeight
  dataForm.cylinderType = val.cylinderType
  pageData.sideTitle = '转机台'
  aspTableColumns
  workshopTask(0)
  processData(val)
}

//已排产修改 弹窗
const editOrder = () => {
  dataForm.flowCardCode = ''
  dataForm.castNum = ''
  pageData.sideTitle = '已排产顺序调整'
  workshopTask(pageData.workshopId2)
}

// 使用concat方法增加动态子表头
const processData = (val: any) => {
  const childColumns = timeTableColumns.find((col: any) => col.headerName === '流转卡工序时间计算')
  if (childColumns) {
    childColumns.children = []
    childColumns.children = val.flowList
      .map((name: any) => ({
        headerName: name,
        field: '',
        width: 100,
      }))
      .concat([
        { headerName: '客户交期', field: 'colorSample', width: 100 },
        { headerName: '排产后交期', field: 'colorSample', width: 100 },
      ])
  }
}

//车间任务发布  已排产顺序调整 转机台
const workshopTask = (workshopId: any) => {
  pageData.sideTitle == '车间任务发布'
    ? (pageData.pageLoading = true)
    : (pageData.pageLoading2 = true)
  let url = pageData.sideTitle == '车间任务发布' ? 'aps/workSequenceTask/findTaskSequenceForScheduling' : 'aps/workSequenceTask/findMachineTaskSequence'
  get({
    url: url,
    data: {
      workshopId: workshopId ? workshopId : 0,
      castNum: dataForm.castNum,
      machineTypeId: 1,
    },
  }).then(({ code, data, message }) => {
    if (code == 200) {
      dataForm.machineCodes = data.machineCodes
      // 推荐机台 赋值
      if (data.recommendMachineCode && pageData.sideTitle == '车间任务发布') {
        let foundEmpty = false
        data.flowCardMachineMap.forEach((o: any) => {
          if (!foundEmpty && !o[data.recommendMachineCode]) {
            o[data.recommendMachineCode] = dataForm.flowCardCode
            foundEmpty = true
            //新增一行空白数据 可拖拽
            const newlist = {}
            data.machineCodes.forEach((code: any) => {
              newlist[code] = ''
            })
            data.flowCardMachineMap.push(newlist)
          }
        })
        //如果推荐机台无位置，新增加一行数据push
        if (!foundEmpty) {
          const newObject = {}
          data.machineCodes.forEach((code: any) => {
            newObject[code] = ''
          })
          newObject[data.recommendMachineCode] = dataForm.flowCardCode
          data.flowCardMachineMap.push(newObject)
        }
      } else if (pageData.sideTitle == '转机台') {
        const newlist = {}
        data.machineCodes.forEach((code: any) => {
          newlist[code] = ''
        })
        data.flowCardMachineMap.push(newlist)
      }
      pageData.apsList = data.flowCardMachineMap

      //拖拽方法
      aspTableColumns.value = []
      const topLevelHeaders = Object.keys(data.machineCodeMap)
      topLevelHeaders.forEach((topHeader) => {
        const subHeaders = data.machineCodeMap[topHeader]
        // 动态多表头
        aspTableColumns.value.unshift({
          headerName: topHeader,
          children: subHeaders.map((res: any) => ({
            headerName: res,
            field: res,
            minWidth: 39,
            width: 100,
            wrapHeaderText: true,
            autoHeaderHeight: true,
            cellStyle: (val: any) => {
              if (pageData.sideTitle != '已排产顺序调整' && val.value == dataForm.flowCardCode) {
                return { backgroundColor: 'skyblue' } //推荐机台底色为蓝色
              }
              return null // 保持原样
            },
            cellRenderer: {
              template: `<div style="width:100px;height:32px;text-align:center;" draggable="true" @dragstart="onDragStart"
                           @dragover="allowDrop" @drop="drop">{{ params.data[val] ? params.data[val].split('_')[0] : '' }}
                       </div>`,
              setup(props: any) {
                const val = ref(res)
                let isRecommendedMachine: any =
                  props.params.data[val.value] == dataForm.flowCardCode // 检查是否是推荐机台列
                //根据条件 是否允许拖拽
                const onDragStart = (event: any) => {
                  if (
                    props.params.data[val.value] &&
                    isRecommendedMachine &&
                    pageData.sideTitle != '已排产顺序调整'
                  ) {
                    event.dataTransfer.setData(
                      'text/col/row',
                      JSON.stringify({
                        text: props.params.data[val.value],
                        col: val.value,
                        row: props.params.rowIndex,
                      })
                    )
                  } else if (
                    props.params.data[val.value] &&
                    pageData.sideTitle == '已排产顺序调整'
                  ) {
                    event.dataTransfer.setData(
                      'text/col/row',
                      JSON.stringify({
                        text: props.params.data[val.value],
                        col: val.value,
                        row: props.params.rowIndex,
                      })
                    )
                  } else {
                    event.preventDefault()
                  }
                }
                // 是否允许放置拖拽的任务
                const allowDrop = (event: any) => {
                  event.preventDefault()
                }
                // 放置任务时调用 获取拖拽的数据并处理
                const drop = (event: any) => {
                  event.preventDefault()
                  const droppedData = JSON.parse(event.dataTransfer.getData('text/col/row'))
                  if (
                    pageData.sideTitle != '已排产顺序调整' ||
                    (pageData.sideTitle === '已排产顺序调整' && droppedData.col === val.value)
                  ) {
                    if (droppedData.col === val.value) {
                      let oldCol = data.flowCardMachineMap.map((o: any) => o[droppedData.col])
                      let oldLine = droppedData.row
                      let desLine = props.params.rowIndex
                      let arr = oldCol.splice(oldLine, 1)
                      oldCol.splice(desLine, 0, arr[0])
                      data.flowCardMachineMap.forEach((o: any, index: number) => {
                        o[val.value] = oldCol[index]
                      })
                    } else {
                      let fromCol = data.flowCardMachineMap.map((o: any) => o[droppedData.col]) //原队列
                      let toCol = data.flowCardMachineMap.map((o: any) => o[val.value]) //新队列
                      let fromLine = droppedData.row //原行
                      let desLine = props.params.rowIndex //目标行
                      let arr = fromCol.splice(fromLine, 1) //删除原行拖动值
                      toCol.splice(desLine, 0, arr[0]) //添加
                      if (toCol[toCol.length - 1]) {  //最后一行数据时自动增加一行
                        const newObject = {}
                        data.machineCodes.forEach((code: any) => {
                          newObject[code] = ''
                        })
                        newObject[data.recommendMachineCode] = dataForm.flowCardCode
                        data.flowCardMachineMap.push(newObject)
                      }
                      data.flowCardMachineMap.forEach((o: any, index: number) => {
                        o[val.value] = toCol[index]
                        o[droppedData.col] = fromCol[index]
                      })
                    }
                    pageData.apsList = data.flowCardMachineMap.filter((row: any) => {
                      return Object.values(row).some((value) => value)  //清除空行
                    })
                  } else if (
                    pageData.sideTitle === '已排产顺序调整' &&
                    droppedData.col !== val.value
                  ) {
                    Message.warning('只可在本列机台下调整顺序！')
                    return
                  }
                }
                return {
                  val,
                  drop,
                  allowDrop,
                  onDragStart,
                  isRecommendedMachine,
                }
              },
            },
          })),
        })
      })
      pageData.apsShow = true
      pageData.pageLoading = false
      pageData.pageLoading2 = false
    } else {
      Message.error(message)
    }
  })
}

const formRef = ref()
const apsOk = () => {
  // pageData.apsList =pageData.apsList.filter((row: any) => {
  //     return Object.values(row).some((value) => value) // 检查每个属性是否都为空
  //   })
  //判断机台中队列是否排满 中间不能有空格
  let invalid = false
  dataForm.machineCodes.forEach((code: any) => {
    let firstPosi = -1
    let resList: any = [...pageData.apsList].reverse()
    resList.forEach((o: any, i: any, index: number) => {
      if (firstPosi === -1) {
        if (o[code]) {
          firstPosi = i
        }
      } else {
        if (!o[code]) {
          invalid = true
          return
        }
      }
    })
  })
  if (invalid) {
    Message.warning('机台队列中间未排满！')
    return
  }

  //保存
  pageData.pageLoading = true
  post({
    url: 'aps/workSequenceTask/updateTaskWithMachineCode',
    data: pageData.apsList.filter((row: any) => {
      return Object.values(row).some((value) => value) // 检查每个属性是否都为空
    })
  }).then(({ code, message }) => {
    if (code == 200) {
      Message.success('成功')
      pageData.apsShow = false
      pageData.pageLoading = false
      doRefresh()
      doRefresh2()
    } else {
      Message.error(message)
    }
  })
}

//设备开停弹窗
const equipmentStart = () => {
  pageData.equipmentShow = true
  equipmentQuery()
}

const equipmentQuery = () => {
  pageData.pageLoading = true
  post({
    url: 'aps/dwMachine/findMachineList',
    data: {
      workshopId: dataForm.workshopId,
      machineTypeId: 1,
    },
  })
    .then(({ data, code }: any) => {
      if (code === 200) {
        pageData.equipmentList = data
      }
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading = false
    })
}

//开停状态
const equipmentCheck = (val: any) => {
  post({
    url: 'aps/dwMachine/updateMachine',
    data: [val],
  }).then(({ code, message }) => {
    if (code == 200) {
      Message.success('成功')
    } else {
      Message.error(message)
    }
  })
}

// 定义调换位置的方法
const transferDown = () => {
  const alreadyOrdered: any = document.getElementById('alreadyOrdered')
  const notOrdered: any = document.getElementById('notOrdered')
  const gang: any = document.getElementById('gang')
  // 获取两个元素的父级节点
  const parent = alreadyOrdered.parentNode
  // 获取两个元素在父级节点中的位置索引
  const indexA = Array.from(parent.children).indexOf(alreadyOrdered)
  const indexB = Array.from(parent.children).indexOf(notOrdered)
  // 将notOrdered插入到alreadyOrdered之前
  parent.insertBefore(notOrdered, alreadyOrdered)
  // 将alreadyOrdered插入到notOrdered原来的位置
  if (indexA < indexB) {
    // 如果alreadyOrdered原来在gang之前，插入到gang之前
    parent.insertBefore(alreadyOrdered, gang.nextSibling)
  } else {
    // 如果alreadyOrdered原来在gang之后，插入到gang之后
    parent.insertBefore(alreadyOrdered, gang)
  }
}

// 顺序调整
const onRowDragEnd = (params: any) => {
  const { overIndex, node } = params
  const draggedRowData = node.data
  const currentIndex = pageData.arrangedList.indexOf(draggedRowData)
  pageData.arrangedList.splice(currentIndex, 1)
  pageData.arrangedList.splice(overIndex, 0, draggedRowData)
  //查找拖动行相同的machineCode
  const draggedMachineCode = draggedRowData.machineCode
  const sameMachineGroup = pageData.arrangedList.filter(
    (item: any) => item.machineCode === draggedMachineCode
  )
  sameMachineGroup.forEach((o: any, index: number) => {
    o.machineOrder = index + 1
  })
  //更新数组
  pageData.arrangedList = [...pageData.arrangedList]
  let list = pageData.arrangedList.filter((o: any) => o.machineCode == draggedMachineCode)
  let data: any = []
  list.forEach((o: any) => {
    let newData = { id: o.taskId, machineOrder: o.machineOrder }
    data.push(newData)
  })
  //实时更新顺序
  post({
    url: 'aps/workSequenceTask/updateTaskMachineOrder',
    data: data,
  }).then((res: any) => {
    if (res.code === 200) {
      doRefresh2()
    } else {
      Message.error(res.message)
    }
  })
}

onMounted(() => {
  pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
  //弹出层的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight
  }
  Query()
})
</script>
<style lang="less" scoped>
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

#gang {
  height: 20px;
  margin-top: 20px;
  margin-bottom: 20px;
  background-color: #f0f2f5;
}

.divInterval {
  border: 2px solid #f0f2f5;
  width: 100%;
  height: 2px;
  margin-top: 10px;
  margin-bottom: 12px;
}

.buttonLeft {
  width: 0px;
  height: 400px;
  color: #fff;
}

.divCenter {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.custom-header-class) {
  background-color: #fff !important;

  &:hover {
    background-color: #fff !important;
  }
}

.table {
  th {
    border: 1px solid #babfc7;
    text-align: center;
    padding: 8px;
  }
}
</style>
